/*
 * @Description: 
 * @Author: hanyu
 * @Date: 2022-03-04 10:37:13
 * @LastEditTime: 2022-03-30 16:51:02
 * @LastEditors: hanyu
 */
import cookie from '@/lib/cookie.js';
import {
    loginApi
} from '@/api/login';
import {
    localSave,
    localRead
} from '@/lib/local';
export default {
    state: {
        token: cookie.getToken(),
        userLoginInfo: null,
    },
    mutations: {
        // 清理指定 storage
        clearLocalStorage() {
            localStorage.removeItem('data-analysis');
        },
        // 设置token
        setToken(state, token) {
            state.token = token;
            cookie.setToken(token);
        },
        // 保存用户登录信息
        setUserLoginInfo(state, userLoginInfo) {
            state.userLoginInfo = userLoginInfo;
            localSave('kfAdminUserLoginInfo', JSON.stringify(userLoginInfo));
        },
    },
    getters: {
        userLoginInfo(state){
            if(state.userLoginInfo){
                return state.userLoginInfo
            }else{
               return JSON.parse(localRead('kfAdminUserLoginInfo'))
            }
        }
    },
    actions: {
        // 登录
        handleLogin({
            commit
        }, params) {
            params.loginName = params.loginName.trim();
            return new Promise((resolve, reject) => {
                loginApi
                    .login(params)
                    .then(res => {
                        commit('clearLocalStorage');
                        const data = res.data;
                        commit('setToken', data.xaccessToken);
                        // 保存用户登录
                        commit('setUserLoginInfo', data);
                        resolve();
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        }
    }
}